<template>
  <div class="pie-chart-wrapper">
    <div ref="pieChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-if="!loading && isEmpty" class="chart-empty">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, onUnmounted, ref, watch} from 'vue'
import * as echarts from 'echarts'
import {Loading} from '@element-plus/icons-vue'
import {postList} from "@/uses/handleData.js";

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据模型
  model: {
    type: String,
    required: false
  },
  // 静态数据（当不使用 model 时）
  data: {
    type: Array,
    default: () => []
  },
  // 数据值字段
  dataKey: {
    type: String,
    default: 'value'
  },
  // 标签字段
  labelKey: {
    type: String,
    default: 'name'
  },
  // 图表高度
  height: {
    type: String,
    default: '350px'
  },
  // 饼图半径
  radius: {
    type: Array,
    default: () => ['45%', '70%']
  },
  // 是否显示图例
  showLegend: {
    type: Boolean,
    default: true
  },
  // 图例位置
  legendPosition: {
    type: String,
    default: 'right', // top, bottom, left, right
    validator: (value) => ['top', 'bottom', 'left', 'right'].includes(value)
  },
  // 是否显示标签
  showLabel: {
    type: Boolean,
    default: false
  },
  // 自定义颜色
  colors: {
    type: Array,
    default: () => [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ]
  },
  // 是否显示为环形图
  isDonut: {
    type: Boolean,
    default: true
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  }
})

const pieChart = ref(null)
let chartInstance = null
const loading = ref(false)
const isEmpty = ref(false)

// 获取图例配置
const getLegendConfig = () => {
  if (!props.showLegend) {
    return { show: false }
  }

  const baseConfig = {
    orient: ['top', 'bottom'].includes(props.legendPosition) ? 'horizontal' : 'vertical',
    type: 'scroll',
    textStyle: {
      fontSize: 12,
      color: '#666'
    },
    pageTextStyle: {
      color: '#999'
    }
  }

  const positions = {
    top: { top: '10', left: 'center' },
    bottom: { bottom: '10', left: 'center' },
    left: { left: '10', top: 'center' },
    right: { right: '10', top: 'center' }
  }

  return {
    ...baseConfig,
    ...positions[props.legendPosition]
  }
}

// 初始化图表配置
const getOption = (data) => {
  const radiusConfig = props.isDonut ? props.radius : '70%'

  return {
    color: props.colors,
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: props.legendPosition === 'top' ? '40' : '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    legend: getLegendConfig(),
    series: [
      {
        name: props.title || '数据统计',
        type: 'pie',
        radius: radiusConfig,
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: props.showLabel,
          formatter: '{b}: {c}\n({d}%)',
          fontSize: 12,
          color: '#666'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: props.showLabel,
          length: 15,
          length2: 10
        },
        data: data,
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: (idx) => idx * 50
      }
    ],
    animation: props.animation
  }
}

// 初始化图表
const initChart = (data) => {
  if (!pieChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(pieChart.value)
  chartInstance.setOption(getOption(data))

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    isEmpty.value = false

    let chartData = []

    // 如果有静态数据，使用静态数据
    if (props.data && props.data.length > 0) {
      chartData = props.data.map(item => ({
        name: item[props.labelKey] || item.name,
        value: item[props.dataKey] || item.value
      }))
    }
    // 否则从 API 加载
    else if (props.model) {
      let res = await postList(props.model, {})
      if (res.code === 200 && res.data && res.data.length > 0) {
        chartData = res.data.map(item => {
          let temp = {}
          temp.name = item[props.labelKey]
          temp.value = item[props.dataKey]
          return temp
        })
        console.info('饼图数据:', chartData)
      }
    }

    // 检查是否有数据
    if (chartData.length === 0) {
      isEmpty.value = true
      return
    }

    await nextTick()
    initChart(chartData)
  } catch (error) {
    console.error('加载饼图数据失败:', error)
    isEmpty.value = true
  } finally {
    loading.value = false
  }
}

// 监听数据变化
watch(() => props.data, () => {
  if (props.data && props.data.length > 0) {
    loadData()
  }
}, { deep: true })

// 监听配置变化
watch(() => [props.colors, props.radius, props.showLegend, props.legendPosition, props.showLabel], () => {
  if (chartInstance) {
    loadData()
  }
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  refresh: loadData,
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.pie-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }

  .chart-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
  }
}
</style>
